package com.kika.obwiki.controller;

import com.kika.obwiki.entity.Ebook;
import com.kika.obwiki.rep.EbookQueryReq;
import com.kika.obwiki.rep.EbookSaveReq;
import com.kika.obwiki.resp.CommonResp;
import com.kika.obwiki.resp.EbookQueryResp;
import com.kika.obwiki.resp.PageResp;
import com.kika.obwiki.service.IEbookService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 电子书 前端控制器
 * </p>
 *
 * @author cr
 * @since 2025-06-22
 */
@RestController
@RequestMapping("/ebook")
public class EbookController {

    @Autowired
    private IEbookService ebookService;

    @GetMapping("/list")
    public CommonResp list(@Valid EbookQueryReq req) {
        CommonResp<PageResp<EbookQueryResp>> resp = new CommonResp<>(true, "查询成功", null);

        PageResp<EbookQueryResp> pageResp = ebookService.listByname(req);
        resp.setContent(pageResp);

        return resp;
    }

    /**
     * 保存电子书
     *
     * @param req 保存请求对象
     * @return 保存结果
     */
    @PostMapping("/save")
    @Operation(summary = "保存电子书", description = "保存电子书信息")
    public CommonResp<String> save(@Valid @RequestBody EbookSaveReq req) {
        // 创建实体对象
        Ebook ebook = new Ebook();
        // 拷贝属性
        BeanUtils.copyProperties(req, ebook);

        // 判断是新增还是更新
        if (ObjectUtils.isEmpty(req.getId())) {
            ebookService.save(ebook);
        } else {
            ebookService.updateById(ebook);
        }

        return new CommonResp<>(true, "保存成功", null);
    }

    @DeleteMapping("/delete/{id}")
    public CommonResp delete(@PathVariable Long id) {
        CommonResp resp = new CommonResp<>();
        ebookService.delete(id);
        return resp;
    }

}
